
//动态生成二维码
var QR = require("../../utils/qrcode.js");

const urlAdd = require('../../utils/config').urlAdd;

const getQrCodeStrUrl = require('../../utils/config').getQrCodeStrUrl;
const openVirtualCardUrl = require('../../utils/config').openVirtualCardUrl;
const app = getApp();
Page({

  data: {
    code: '请将二维码对准扫码口进行扫码',
    canvasHidden: false,
    imagePath: '',
    returnData: '',
    stuCode: wx.getStorageSync('stuCode'),
    // 存储定时器
    setInter: '',
  },


  

  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: "我的虚拟卡",
    });
    var that = this;
    // that.getUserLogin();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    that.getUserLogin();
  },

//判断是否授权登录
getUserLogin: function(){
  var that= this;
   // 判断是否授权
   if (wx.getStorageSync('openId') != '') {
    if (wx.getStorageSync('token') == '' || wx.getStorageSync('token') == null) {
        wx.showToast({
          title: '你已授过权, 请登录',
        })
        wx.redirectTo({
          url: '../../pages/login/login?openId=' + wx.getStorageSync('openId')
        })
      } else {
        
        that.getQrCodeStr();
        //调用定时刷新
        that.autoRefresh();
      }
    } else {
      wx.showModal({
        title: '提示',
        content: '你还未授权登录，是否授权登录',
        cancelText: '取消',
        cancelColor: 'red',
        confirmText: '确认',
        confirmColor: '#30a1db',
        success: function (res) {
          //点击取消
          if (res.cancel) {
              wx.switchTab({
                url: '../../pages/index/index',
              })
          } else {
            //点击确定
            wx.redirectTo({
              url: '../../pages/userlogin/login'
            })
          }

        },
        fail: function () {
        }
      })
    }
},






  //获取虚拟卡二维码
  getQrCodeStr: function () {
    var that = this;
    wx.request({
      url: getQrCodeStrUrl,
      method: 'POST',
      header: {
        'Authorization':'Bearer '+ wx.getStorageSync('token')
      },
      // 601 无   602 异常
      success: function (res) {
        wx.hideLoading();
        if (res.data.code == 200) {
          if (res.data.data != null) {
            console.log(res.data.data);
            var size = that.setCanvasSize(); //动态设置画布大小	
            that.setData({
              returnData: res.data.data
            })
            that.createQrCode("mycanvas", size.w, size.h);
          }
        }
        if (res.data.code == 401) {
          wx.showModal({
            title: '提示',
            content: '登录已过期，请重新登录',
            showCancel: false,
            success: function (res) {
              wx.redirectTo({
                url: '../../pages/userlogin/login'
              });
            },
          })
        }
        if (res.data.code == 500) {
          wx.showModal({
            title: '提示',
            content: res.data.msg,
            showCancel: false,
            success: function (res) {
               
            },
          })
        }
        if (res.data.code == 2404) {
          wx.showModal({
            title: '提示',
            content: res.data.msg,
            showCancel: false,
            success: function (res) {
               that.openVirtualCard();
            },
          })
        }
        
      }
    });
  },

  openVirtualCard: function(){
    var that = this;
    wx.request({
      url: openVirtualCardUrl ,
      method: 'POST',
      header: {
        'Authorization':'Bearer '+ wx.getStorageSync('token')
      },
      success: function (res) {
        if (res.data.code == 200) {
          wx.showToast({
            title: '开通成功',
            duration: 3000
          });
          
        }
        if (res.data.code == 500) {
          wx.showModal({
            title: '提示',
            content: '开通虚拟卡失败',
            showCancel: false,
            success: function (res) {
              wx.navigateBack({
                delta: 1
              })
            }
          })
        }
      }
    })
  },

  //适配不同屏幕大小的canvas
  setCanvasSize: function () {
    var size = {};
    try {
      var res = wx.getSystemInfoSync();
      var scale = 750 / 480; //不同屏幕下canvas的适配比例；设计稿是750宽  480是因为样式wxss文件中设置的大小

      var width = res.windowWidth / scale;
      var height = width; //canvas画布为正方形
      size.w = width;
      size.h = height;
    } catch (e) {
      // Do something when catch error
      console.log("获取设备信息失败" + e);
    }
    return size;
  },

  /**
   * 绘制二维码图片
   */
  createQrCode: function (canvasId, cavW, cavH) {
    var that = this;
    if (that.data.returnData != '') {
      // console.log('当前生成时间是。。。。', ct)
      //调用插件中的draw方法，绘制二维码图片
      QR.api.draw(that.data.returnData, canvasId, cavW, cavH);
      setTimeout(() => {
        this.canvasToTempImage(canvasId);
      }, 500);
    } else {
      wx.showModal({
        title: '获取虚拟卡失败',
        content: '请尝试手动刷新或联系管理员',
        showCancel: false,
        confirmText: '确认',
        confirmColor: '#30a1db',
        success: function (res) {
          
        },
      })
    }
  },

  /**
   * 获取临时缓存照片路径，存入data中
   */
  canvasToTempImage: function () {
    var that = this;
    //把当前画布指定区域的内容导出生成指定大小的图片，并返回文件路径。
    wx.canvasToTempFilePath({
      canvasId: 'mycanvas',
      success: function (res) {
        var tempFilePath = res.tempFilePath;
        console.log('生成临时图片路径。。。。' + tempFilePath);
        that.setData({
          imagePath: tempFilePath,
          // canvasHidden:true
        });
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },

  /**
   * 点击图片进行预览
   */
  previewImg: function (e) {
    var img = this.data.imagePath;
    console.log(img);
    wx.previewImage({
      current: img, // 当前显示图片的http链接
      urls: [img] // 需要预览的图片http链接列表
    });
  },

  //定时刷新
  autoRefresh: function () {
    let that = this;
    //定义定时器
    that.data.setInter = setInterval(function () {
      that.getQrCodeStr(); //获取虚拟卡二维码
      console.log('定时一次', Date.parse(new Date()));
      // that.createQrCode("mycanvas", size.w, size.h)
    }, 10000);
  },

  //手动刷新
  manuRefresh: function () {
    wx.showLoading({
      title: '正在刷新...',
    })
    let that = this;
    console.log('手动刷新');
    that.getQrCodeStr();
  },


  //交易记录
  transaction: function (event) {
    var stuCode = event.currentTarget.dataset.stucode;
    console.log(stuCode);
    wx.navigateTo({
      url: '../transaction/transaction?stuCode=' + stuCode,
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    let that = this;
    let setInter = that.data.setInter;
    clearInterval(setInter);
  },
  onHide: function () {
    let that = this;
    let setInter = that.data.setInter;
    clearInterval(setInter);
  }
})